package remote

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"time"
)

type EzRequest struct {
	TimeOut time.Duration
}

func NewEzRequest() *EzRequest {
	return &EzRequest{
		TimeOut: time.Second * 30,
	}
}

func (r *EzRequest) PostMessage(url string, data interface{}) (*http.Response, error) {
	client := &http.Client{
		Timeout: r.TimeOut,
		Transport: &http.Transport{
			DisableKeepAlives: true,
		},
	}
	content, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}

	return client.Post(url, "application/json", bytes.NewReader(content))
}

type Message struct {
	Code    int64       `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

func NewMessageFrom(resp *http.Response) (*Message, error) {
	defer resp.Body.Close()
	message := new(Message)
	//读取resp.Body
	buf, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	e := json.Unmarshal(buf, message)
	if e != nil {
		return nil, e
	}
	return message, nil
}

func (m *Message) GetData(wanted interface{}) error {
	buf, e := json.Marshal(m.Data)
	if e != nil {
		return e
	}
	return json.Unmarshal(buf, wanted)
}
